package com.xiaobing.auth.service.login;


import com.xiaobing.auth.dao.SysUserMapper;
import com.xiaobing.auth.feign.SysUserInfoCenterFeign;
import com.xiaobing.common.constant.CacheConstants;
import com.xiaobing.common.constant.UserConstants;
import com.xiaobing.common.core.Convert;
import com.xiaobing.common.entity.system.SysUser;
import com.xiaobing.common.exception.ExceptionCodeMsg;
import com.xiaobing.common.exception.ServiceException;
import com.xiaobing.common.povo.LoginUser;
import com.xiaobing.common.redis.RedisService;
import com.xiaobing.common.res.Result;
import com.xiaobing.common.utils.IpUtils;
import com.xiaobing.common.utils.StringUtils;
import com.xiaobing.common.utils.UserStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author xulk
 */
@Component
public class SysLoginService {

    @Resource
    private RedisService redisService;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserInfoCenterFeign sysUserInfoCenterFeign;


    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new ServiceException(ExceptionCodeMsg.USERNAME_PASSWORD_IS_NULL);
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException(ExceptionCodeMsg.PASSWORD_LENGTH);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException(ExceptionCodeMsg.USERNAME_LENGTH);
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            throw new ServiceException(ExceptionCodeMsg.IP_BLACKLIST); // "很遗憾，访问IP已被列入系统黑名单"
        }
        // 查询用户信息
        Result<LoginUser> userResult = sysUserInfoCenterFeign.findSysUserInfoByUserName(username);
        if (userResult.getCode() != 200) {
            throw new ServiceException(userResult.getMessage());
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userInfo.getSysUser();
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new ServiceException("对不起，您的账号：" + username + " 已停用"); //
        }
        passwordService.validate(user, password);
        return userInfo;
    }


}
